<!--
 * @Description: 使用 — 入门篇2;
 * @Author: CcSimple
 * @Github: https://github.com/CcSimple
 * @Date: 2023-02-07 11:52:50
 * @LastEditors: CcSimple
 * @LastEditTime: 2023-02-11 15:50:41
-->
<template>
  <div>
    <div class="flex-row justify-center" style="margin-bottom: 10px">
      <div class="paper">
        <template v-for="(value, type) in paperTypes">
          <button :class="curPaperType === type ? 'api' : 'info'" @click="setPaper(type, value)">
            {{ type }}
          </button>
        </template>
        <!-- 自定义纸张 -->
        <button :class="'other' == curPaperType ? 'api' : 'info'" class="auto" @click="showPaperPop">自定义纸张</button>
        <div class="popover">
          <div class="popover-content flex-col" v-show="paperPopVisible">
            <div style="font-size: 16px; font-weight: bold">设置纸张宽高(mm)</div>
            <div class="flex-row mt-10">
              <input class="input" v-model="paperWidth" type="number" placeholder="宽(mm)" />
              <span class="ml-10 mr-10">x</span>
              <input class="input" v-model="paperHeight" type="number" placeholder="高(mm)" />
            </div>
            <button class="primary circle-10" style="margin-top: 6px" @click.stop="setPaperOther">确定</button>
          </div>
        </div>
      </div>
      <el-button @click="save">保存</el-button>
      <el-button @click="reset">还原</el-button>
      <el-button @click="clearPaper">清空</el-button>
      <button class="secondary circle-10 ml-10" @click.stop="print">
        <i class="iconfont sv-printer" />
        浏览器打印
      </button>
    </div>
    <div class="flex-row" style="height: 87vh">
      <div class="flex-2 left flex-col">
        <div class="title"></div>
        <!-- provider1 的容器; 加上 class "rect-printElement-types" 使用默认样式 -->
        <!-- 当然可以 重写 或者 自定义样式 -->
        <div id="provider-containerLocation" class="container rect-printElement-types"></div>
        <div class="title"></div>
        <!-- provider2 的容器; -->
        <!-- 这里自定义显示样式 custom-style-types -->
        <div id="provider-containerLocation2" class="container custom-style-types"></div>
        <div class=""></div>
      </div>
      <div class="flex-5 center">
        <!-- 设计器的 容器 -->
        <div id="hiprint-printTemplateLocation"></div>
      </div>
      <div class="flex-2 right">
        <!-- 元素参数的 容器 -->
        <div id="PrintElementOptionSettingLocation"></div>
      </div>
    </div>
  </div>
</template>
<script>
  import {
    hiprint
  } from "vue-plugin-hiprint";
  import {
    provider1
  } from "./provider1";
  import {
    provider2
  } from "./provider2";
  // 工具
  import {
    newHiprintPrintTemplate
  } from "@/utils/template-helper";
  import {
    createQrCodeN
  } from "@/api/basic/PersonnelInformation.js";
  import locationTemp from './locationTemp.js'
  let templateRef = locationTemp;
  export default {
    data() {
      return {
        pageNum: 0, //用的哪个模板
        // 当前纸张
        curPaper: {
          type: 'other',
          width: 220,
          height: 80
        },
        // 纸张类型
        paperTypes: {
          'A3': {
            width: 420,
            height: 296.6
          },
          'A4': {
            width: 210,
            height: 296.6
          },
          'A5': {
            width: 210,
            height: 147.6
          },
          'B3': {
            width: 500,
            height: 352.6
          },
          'B4': {
            width: 250,
            height: 352.6
          },
          'B5': {
            width: 250,
            height: 175.6
          }
        },
        // 自定义纸张
        paperPopVisible: false,
        paperWidth: '220',
        paperHeight: '80',
        // 自定义传入 provider 的参数
        options: {
          config: {
            tid: "providerModule1.config",
            title: "销售出库单",
            type: "text",
            options: {
              testData: "",
              height: 30,
              fontSize: 16,
            },
          },
        },
        hiprintTemplate: null
      }
    },
    mounted() {
      // 初始化 provider
      hiprint.init({
        providers: [provider1(this.options), provider2(this.options)],
      });
      this.buildLeftElement();
      this.buildDesigner();
    },
    computed: {
      curPaperType() {
        let type = 'other'
        let types = this.paperTypes
        for (const key in types) {
          let item = types[key]
          let {
            width,
            height
          } = this.curPaper
          if (item.width === width && item.height === height) {
            type = key
          }
        }
        return type
      }
    },
    methods: {
      //清空
      clearPaper() {
        try {
          this.hiprintTemplate.clear();
        } catch (error) {
          this.$message.error(`操作失败: ${error}`);
        }
      },
      //自定义确定按钮
      setPaperOther() {
        let value = {}
        value.width = this.paperWidth
        value.height = this.paperHeight
        this.paperPopVisible = false
        this.setPaper('other', value)
      },
      //自定义显示隐藏
      showPaperPop() {
        this.paperPopVisible = true;
      },
      hidePaperPop() {
        this.paperPopVisible = false;
      },
      /**
       * 设置纸张大小
       * @param type [A3, A4, A5, B3, B4, B5, other]
       * @param value {width,height} mm
       */
      setPaper(type, value) {
        try {
          if (Object.keys(this.paperTypes).includes(type)) {
            this.curPaper = {
              type: type,
              width: value.width,
              height: value.height
            }
            this.hiprintTemplate.setPaper(value.width, value.height)
          } else {
            this.curPaper = {
              type: 'other',
              width: value.width,
              height: value.height
            }
            this.hiprintTemplate.setPaper(value.width, value.height)
          }
        } catch (error) {
          this.$message.error(`操作失败: ${error}`)
        }
      },
      buildLeftElement() {
        $("#provider-containerLocation").empty(); // 先清空, 避免重复构建
        hiprint.PrintElementTypeManager.build($("#provider-containerLocation"), "providerModule1");
        $("#provider-containerLocation2").empty(); // 先清空, 避免重复构建
        hiprint.PrintElementTypeManager.build($("#provider-containerLocation2"), "providerModule2");
      },
      //设计页面
      buildDesigner() {
        // eslint-disable-next-line no-undef
        $("#hiprint-printTemplateLocation").empty(); // 先清空, 避免重复构建
        let templates = this.$ls.get('KEY_TEMPLATES', {})
        let template = templates['NAME'] ? templates['NAME'] : templateRef
        this.hiprintTemplate = new hiprint.PrintTemplate({
          // template: templateRef,
          template: template ? template : templateRef, // 模板json(object)
          settingContainer: "#PrintElementOptionSettingLocation", // 元素参数容器
          //图片选择
          onImageChooseClick: (target) => {
            // 创建input，模拟点击，然后 target.refresh 更新
            let input = document.createElement("input");
            input.setAttribute("type", "file");
            input.click();
            input.onchange = function() {
              var file = this.files[0];
              var reader = new FileReader();
              if (file) {
                var reader = new FileReader();
                //通过文件流行文件转换成Base64字行串
                reader.readAsDataURL(file);
                //转换成功后
                reader.onloadend = function() {
                  // 通过 target.refresh 更新图片元素
                  target.refresh(reader.result);
                }
              }
            }
            input.remove();
          },
        });
        // 构建 并填充到 容器中
        // 可以先 console.log($("#hiprint-printTemplate")) 看看是否有该 dom
        this.hiprintTemplate.design("#hiprint-printTemplateLocation");
      },
      //保存模板
      save() {
        this.setTemplate({
          name: 'NAME',
          json: this.hiprintTemplate.getJson()
        })
      },
      removeTemplate(payload) {
        let templates = this.$ls.get('KEY_TEMPLATES', {})
        templates[payload.name] = payload.json
        templates[payload.name] = templateRef;
        this.$ls.set('KEY_TEMPLATES', templates)
         this.$ls.clear(); // 清空所有存储
        this.buildDesigner();
        this.$message.info('还原成功')
      },
      //还原
      reset() {
        this.removeTemplate({
          name: 'NAME',
          json: this.hiprintTemplate.getJson()
        })
      },
      //设置模板
      setTemplate(payload) {
        let templates = this.$ls.get('KEY_TEMPLATES', {})
        templates[payload.name] = payload.json
        this.$ls.set('KEY_TEMPLATES', templates)
        this.$message.info('保存成功')
      },
      //浏览器打印
      print(data) {
        // 打印数据，key 对应 元素的 字段名
        let printData = data;
        // 参数: 打印时设置 左偏移量，上偏移量
        let options = {
          leftOffset: -1,
          topOffset: -1
        };
        // 扩展
        let ext = {
          callback: () => {
            console.log("浏览器打印窗口已打开");
          },
          // styleHandler: () => {
          //   // 重写 文本 打印样式
          //   return "<style>.hiprint-printElement-text{color:red !important;}</style>";
          // },
        }
        // 调用浏览器打印
        this.hiprintTemplate.print(printData,options, ext);
      }
    }
  }
</script>

<style scoped>
  /* 重写默认的一个样式 */
  .rect-printElement-types .hiprint-printElement-type>li>ul>li>a {
    color: #333333 !important;
  }

  /* 自定义 provider 构建样式 */
  .custom-style-types .hiprint-printElement-type {
    display: block;
  }

  .custom-style-types .hiprint-printElement-type {
    padding: 0 0 0 0;
    list-style: none;
  }

  .custom-style-types .hiprint-printElement-type>li>.title {
    display: block;
    padding: 4px 0px;
    color: rgb(0, 58, 230);
    clear: both;
  }

  .custom-style-types .hiprint-printElement-type>li>ul {
    padding: 0 0 0 0;
    display: block;
    list-style: none;
  }

  /* 修改 页眉/页脚线 样式 */
  .hiprint-headerLine,
  .hiprint-footerLine {
    border-color: red !important;
  }

  .hiprint-headerLine:hover,
  .hiprint-footerLine:hover {
    border-top: 3px dashed red !important;
  }

  .hiprint-headerLine:hover:before {
    content: "页眉线";
    left: calc(50% - 18px);
    position: relative;
    background: #ffff;
    top: -12px;
    color: red;
    font-size: 12px;
  }

  .hiprint-footerLine:hover:before {
    content: "页脚线";
    left: calc(50% - 18px);
    position: relative;
    color: red;
    background: #ffff;
    top: -12px;
    font-size: 12px;
  }

  .custom-style-types .hiprint-printElement-type>li>ul>li {
    display: block;
    width: 50%;
    float: left;
    max-width: 100px;
  }

  .custom-style-types .hiprint-printElement-type>li>ul>li>a {
    padding: 12px 6px;
    color: #1296db;
    text-decoration: none;
    background: #fff;
    border: 1px solid #ddd;
    margin-right: 5px;
    width: 95%;
    max-width: 100px;
    display: inline-block;
    text-align: center;
    margin-bottom: 7px;
    box-sizing: border-box;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 4px;
    box-shadow: 0 1px 0 0 rgba(0, 0, 0, 0.15);
  }
</style>

<style scoped>
  /* api按钮 */
  .api {
    background: #00acc1;
  }

  .auto {
    width: auto !important;
  }

  /* 纸张 */
  .paper {
    margin-right: 10px;
  }

  .paper button:not(class*="auto") {
    width: 60px !important;
  }

  /* 多个 button 间距 */
  .paper button+button {
    margin-left: -1px;
  }

  .paper button:first-child:last-child {
    border-radius: 4px;
  }

  /* 两边的 btn 圆角 */
  .paper button:first-child:not(:last-child) {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }

  .paper button:last-child:not(:first-child) {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }

  .popover {
    position: absolute;
    margin-top: 10px;
    z-index: 10;
  }

  .popover .popover-content {
    background: white;
    border-radius: 4px;
    padding: 10px 14px;
    box-shadow: 2px 2px 2px 4px rgb(128 0 128 / 20%);
  }

  .popover .input {
    height: 24px;
    padding: 2px 4px;
  }

  .popover .input:hover {
    border-color: rgb(245, 155, 241);
    border-radius: 4px;
  }

  /* 区域 */
  .left {
    background: white;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    box-shadow: 2px 2px 2px 0px rgb(128 0 128 / 20%);
    overflow: auto;
  }

  .left .container {
    height: 50%;
    overflow: auto;
    padding: 0 10%;
  }

  .left .container[id*="provider-container2"] {
    margin-bottom: 10px;
    background: rgb(209, 120, 239);
  }

  .center {
    margin: 0 10px;
    background: white;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 20px;
    box-shadow: 2px 2px 2px 0px rgb(128 0 128 / 20%);
    overflow: auto;
  }

  .right {
    background: white;
    border-radius: 4px;
    border: 1px solid #d9d9d9;
    padding: 10px 0;
    box-shadow: 2px 2px 2px 0px rgb(128 0 128 / 20%);
    overflow: auto;
  }

  /* 左侧拖拽元素样式 */
  .title {
    font-size: 16px;
    font-weight: 500;
    margin: 4px 0 4px 10px;
  }

  .item {
    display: flex;
    flex-direction: column;
    align-items: center;
    background: white;
    padding: 4px 10px;
    margin: 10px 8px 4px 8px;
    width: 38%;
    min-height: 60px;
    border-radius: 4px;
    box-shadow: 2px 2px 2px 2px rgba(171, 171, 171, 0.2);
  }

  .item .iconfont {
    font-size: 1.5rem;
  }

  .item span {
    font-size: 14px;
  }
</style>
